package com.toogu.mazhangmen.ui.monitor;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.toogu.mazhangmen.bean.EquipmentsBean;
import com.toogu.mazhangmen.bean.QATypeBean;
import com.toogu.mazhangmen.bean.SockReturnBean;
import com.toogu.mazhangmen.service.SockService;
import com.toogu.mazhangmen.ui.login.LoginContract;
import com.toogu.mazhangmen.ui.view.RadioGroupView;
import com.toogu.mazhangmen.util.AlarmUtil;
import com.toogu.mazhangmen.util.EquipmentUtil;
import com.toogu.mazhangmen.util.MonitorUtil;
import com.toogu.mazhangmen.util.NetWorkUtil;
import com.toogu.mazhangmen.util.PopUtil;
import com.toogu.mazhangmen.util.ToastUtil;

import java.util.List;
import java.util.Queue;

import static android.content.Context.BIND_AUTO_CREATE;

public class ControlPresenter implements ControlContract.IPresenter{
    private ControlContract.IView view = null;
    private ControlContract.IModel model = null;
    private Activity activity = null;
    private EquipmentsBean equipmentsBean;
    private String doorId;
    private MonitorUtil monitorUtil;
    private SockService.SockBinder mBinder;

    public ControlPresenter(Activity activity, EquipmentsBean equipmentsBean, MonitorUtil monitorUtil){
        this.activity=activity;
        this.equipmentsBean =equipmentsBean;
        this.monitorUtil=monitorUtil;
        doorId  = equipmentsBean.getDoor()==null?"-1":equipmentsBean.getDoor().getId();
    }
    @Override
    public void onCreate(ControlContract.IView view, ControlContract.IModel model) {
        this.view = view;
        this.model = model;
        view.setViewDelegate(IViewDelegate);
        model.setModelDelegate(IModelDelegate);

        if(equipmentsBean.getDoor()!=null){
            model.setPersonShow(equipmentsBean.getProject_id(),equipmentsBean.getDoor().getId());
        }

        view.onCreate();
        model.onCreate();
    }

    @Override
    public void onResume() {
        activity.bindService(new Intent(activity, SockService.class),serviceConnection, BIND_AUTO_CREATE);//连接服务
        view.onResume();
        model.onResume();
    }

    @Override
    public void onPause() {
        if(mBinder!=null) {//关闭服务链接
            mBinder.onUnbind(1);
            activity.unbindService(serviceConnection);
            mBinder=null;
        }
        view.onPause();
        model.onPause();
    }

    @Override
    public void onDestory() {
        view.onDestory();
        model.onDestory();
    }

    //服务连接
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (SockService.SockBinder) service;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private ControlContract.IView.Delegate IViewDelegate = new ControlContract.IView.Delegate() {
        private SockService.OnProgressListener  onProgressListener = new SockService.OnProgressListener() {
            @Override
            public void onSockCallbackProgress(Queue<SockReturnBean> queue) {
                while (!queue.isEmpty()) {
                    SockReturnBean sockReturnBean = queue.poll();
                    Log.d("mBinder", "onProgress: " + "" + new Gson().toJson(sockReturnBean));

                    if (sockReturnBean.getCode().equals("1")) {//1表示异常
                        activity.runOnUiThread(() -> {
                            Toast.makeText(activity, sockReturnBean.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                    else {//表示抓拍正常
                        activity.runOnUiThread(() -> {
                            switch (sockReturnBean.getStatus()) {
                                case "1"://启动抓拍
                                    Toast.makeText(activity, sockReturnBean.getMessage(), Toast.LENGTH_SHORT).show();
                                    break;
                                case "2"://新用户抓拍成功
                                    Toast.makeText(activity, "新用户抓拍"+sockReturnBean.getMessage(), Toast.LENGTH_SHORT).show();
                                    view.showPersonImage(sockReturnBean.getFilename());
                                    break;
                                case "3"://系统重复抓拍
                                    Toast.makeText(activity, "系统重复抓拍"+sockReturnBean.getMessage(), Toast.LENGTH_SHORT).show();
                                    break;
                                case "4"://老用户抓拍成功
                                    Toast.makeText(activity, "老用户抓拍"+sockReturnBean.getMessage(), Toast.LENGTH_SHORT).show();
                                    break;
                            }
                            model.getTempRecord(sockReturnBean.getPhonenum(),sockReturnBean.getParkid());//获取价钱
                        });
                    }
                }
            }
        };


        private View.OnClickListener ControlListener = new View.OnClickListener() {
            boolean isTalk = false;
            boolean isVoice = false;
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case 1:
                        if (monitorUtil.getIsConnected())
                            NetWorkUtil.getNetWorkUtil().allOpen(activity, doorId, true, equipmentsBean.getName());
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        if (monitorUtil.getIsConnected())
                            NetWorkUtil.getNetWorkUtil().allOpen(activity, doorId, false, equipmentsBean.getName());
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        if (monitorUtil.getIsConnected())
                            NetWorkUtil.getNetWorkUtil().close(activity, doorId, equipmentsBean.getName());
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 4:
                        if (monitorUtil.getIsConnected())
                            NetWorkUtil.getNetWorkUtil().halfOpen(activity, doorId,true, equipmentsBean.getName());
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 5:
                        if (monitorUtil.getIsConnected())
                            NetWorkUtil.getNetWorkUtil().halfOpen(activity, doorId,false, equipmentsBean.getName());
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 6:
                        if(monitorUtil.getIsConnected()) {
                            if (!isVoice) {
                                PopUtil.showTalk(activity, monitorUtil);
                            } else {
                                Toast.makeText(activity, "请先关闭音频", Toast.LENGTH_SHORT).show();
                            }
//                                if(!isTalk){
//                                    ((TextView)v).setText("关闭对话");
//                                    monitorUtil.openTalk();
//                                }
//                                else{
//                                    ((TextView)v).setText("对讲");
//                                    monitorUtil.closeTalk();
//                                }
//                                isTalk=!isTalk;
                        }
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 7:
                        if(monitorUtil.getIsConnected()){
                            if(AlarmUtil.getInstance().setLanAlarm(equipmentsBean,true)){
                                ToastUtil.getToastUtil().add(equipmentsBean.getName()+"打开警报成功");
                            }else{
                                Toast.makeText(activity, "打开警报失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 8:
                        if(monitorUtil.getIsConnected()){
                            if(AlarmUtil.getInstance().setLanAlarm(equipmentsBean,false)){
                                ToastUtil.getToastUtil().add(equipmentsBean.getName()+"关闭警报成功");
                            }else{
                                Toast.makeText(activity, "关闭警报失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 9:
                        if(monitorUtil.getIsConnected()){
                            if(!isVoice){
                                ((TextView)v).setText("关闭音频");
                                monitorUtil.openVoice();
                            }
                            else{
                                ((TextView)v).setText("打开音频");
                                monitorUtil.closeVoice();
                            }
                            isVoice=!isVoice;
                        }
                        else
                            Toast.makeText(activity, "监控未连接", Toast.LENGTH_SHORT).show();
                        break;
                    case 10:
                        EquipmentUtil.closeHelp(equipmentsBean.getCode());
                        monitorUtil.getMonitorView().closeHelp();
                        break;
                    case 11:
                        model.getQAType();
//                        PopUtil.showQACall(activity,equipmentsBean);
                        break;

                }
            }
        };
        @Override
        public View.OnClickListener getControlListener() {
            return ControlListener;
        }

        @Override
        public View.OnClickListener getTakePhoto() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ControlContract.AccessOutRecordBean accessOutRecordBean = (ControlContract.AccessOutRecordBean) v.getTag();
                    if (mBinder == null) {
                        Toast.makeText(activity, "服务未连接", Toast.LENGTH_SHORT).show();
                    } else if (accessOutRecordBean.getUser().getMobile() == null) {
                        Toast.makeText(activity, "用户信息不存在", Toast.LENGTH_SHORT).show();
                    } else {
                        JsonObject object = new JsonObject();
                        object.addProperty("parkid", equipmentsBean.getProject_id());
                        object.addProperty("doorid", equipmentsBean.getDoor().getId());
                        object.addProperty("phonenum", accessOutRecordBean.getUser().getMobile());
                        object.addProperty("messagetype", "1");
                        object.addProperty("direction", (Integer.parseInt(accessOutRecordBean.getType()) - 1) + "");
                        mBinder.takePhoto(object.toString(),onProgressListener);
                    }
                }
            };
        }

        @Override
        public View.OnClickListener getPaySubmit() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String id = (String) v.getTag();
                    NetWorkUtil.getNetWorkUtil().putTemporaryConfirm(activity,id);
                }
            };
        }

        @Override
        public RadioGroupView.OnCheckedChangeListener getOnCheckedChangeListener() {
            return new RadioGroupView.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(int situation) {
                    doorId = equipmentsBean.getDoors().get(situation).getId();
                    model.setPersonShow(equipmentsBean.getProject_id(),doorId);
                }
            };
        }

    };

    private ControlContract.IModel.Delegate IModelDelegate = new ControlContract.IModel.Delegate() {

        @Override
        public void onDataChanged(ControlContract.AccessOutRecordBean accessOutRecordBean) {
            view.setPerson(accessOutRecordBean);
        }

        @Override
        public void showPay(ControlContract.TempRecord tempRecord) {
            view.showPay(tempRecord);
        }

        @Override
        public void showQA(List<QATypeBean> qaTypeBeanList) {
            PopUtil.showQACall(activity,equipmentsBean,qaTypeBeanList);
        }
    };
}
